import type { TradeSchema } from "@/types/account.types";
import { computed } from "vue";
import dayjs from "dayjs";
import { useBreakpointQuery } from "@/utils/device";
import {
  renderDatetimeCell,
  renderNumberCell,
  renderSymbolCell,
  renderTextCell
} from "@/utils/cell";

export const useTradeTable = (forceCompact = false) => {
  const { isMdUp } = useBreakpointQuery();

  const tableSize = computed(() => {
    if (forceCompact) {
      return "small";
    }
    if (isMdUp()) {
      return "default";
    }
    return "small";
  });

  const datetimeFormat = computed(() => {
    if (forceCompact) {
      return "HH:mm:ss";
    }
    if (isMdUp()) {
      return "YYYY-MM-DD HH:mm:ss";
    }
    return "HH:mm:ss";
  });

  const getTradeColumns = () => {
    const columns: TableColumnList = [
      {
        label: "合约",
        prop: "symbol",
        minWidth: 120,
        showOverflowTooltip: true,
        sortable: true,
        formatter: (row: TradeSchema) => renderSymbolCell(row.symbol)
      },
      {
        label: "方向",
        prop: "direction",
        minWidth: 80,
        sortable: true,
        formatter: (row: TradeSchema) =>
          renderTextCell(
            row.direction ? `${row.direction}${row.offset}` : "-",
            row.direction === "多"
              ? "text-text_red_text"
              : "text-text_green_text"
          )
      },
      {
        label: "价格",
        prop: "price",
        align: "right",
        minWidth: 100,
        sortable: true,
        sortMethod: (a: TradeSchema, b: TradeSchema) => a.price - b.price,
        formatter: (row: TradeSchema) =>
          renderNumberCell(row.price, 2, false, false)
      },
      {
        label: "数量",
        prop: "volume",
        align: "right",
        minWidth: 80,
        sortable: true,
        sortMethod: (a: TradeSchema, b: TradeSchema) => a.volume - b.volume,
        formatter: (row: TradeSchema) =>
          renderNumberCell(row.volume, 0, false, false)
      },
      {
        label: "成交时间",
        prop: "event_time",
        minWidth: 140,
        sortable: true,
        sortMethod: (a: TradeSchema, b: TradeSchema) => {
          const ta = a.event_time ? dayjs(a.event_time).valueOf() : -Infinity;
          const tb = b.event_time ? dayjs(b.event_time).valueOf() : -Infinity;
          return ta - tb;
        },
        formatter: (row: TradeSchema) =>
          renderDatetimeCell(row.event_time, datetimeFormat.value)
      }
    ];

    return columns;
  };

  const tradeColumns = computed(() => getTradeColumns());
  return { tradeColumns, tableSize };
};
